import {Component} from "@angular/core";
import {ActivatedRoute, Router} from "@angular/router";
import {NzModalService, NzModalSubject, NzNotificationService} from "ng-zorro-antd";
import {HttpServcie} from "../../../service/http.service";
import {TrainingPlanDetailBean} from "../bean/trainingPlanDetail.bean";
import {Config} from "../../../service/config";
import {isNull} from "util";


@Component({
  selector: "trainingPlan-detail-page",
  templateUrl: "trainingPlan-detail.html",
  styleUrls: ["trainingPlan-detail.scss"]
})

export class TrainingPlanDetail {
  trainingPlan : any = {};
  trainingPlanDetail : TrainingPlanDetailBean = new TrainingPlanDetailBean();
  config = Config;
  partyTypes = Config.PARTY_TYPE;
  planStatus = Config.PLAN_STATUS;
  constructor(
    private httpService: HttpServcie,
    private router: Router,
    private activatedRoute: ActivatedRoute,
    private _notification: NzNotificationService,
    private nsub: NzModalSubject,
    private modalService: NzModalService
  ) {
    this.activatedRoute.params.subscribe(data => {
      //深度 clone 一下，否则不能修改
      this.trainingPlan = Object.assign({}, data);
      this.trainingPlanDetail.planId = this.trainingPlan.id;
    });
  }
  partyType : string = "";
  modelTitle : string = "";
  modal: any = 0;
  currentModal: NzModalSubject;
  startDate : string = "";
  endDate : string = "";
  planName : string = "";
  planType : string = "";
  userId : string = "";
  //返回的集合
  dataList : any = [];
  //多选框
  allChecked: any = false;
  //多选框
  indeterminate: any = false;
  total : number;
  updateData: any = {};
  sendTitle : String = "";
  sendContent : string = "";
  ngOnInit(){
    this.partyType = JSON.parse(window.localStorage.getItem("user")).partyType;
    this.userId = JSON.parse(window.localStorage.getItem("user")).id;
    this.trainingPlanDetail.currentPage = 1;
    this.trainingPlanDetail.pageSize = 10;
    this.query();
  }

  query(){
    this.trainingPlanDetail.leadUnit = JSON.parse(window.localStorage.getItem("user")).partyName;
    this.httpService.queryTrainingPlanDetail(this.trainingPlanDetail).subscribe(data => {
      if (data.status == "200") {
        this.dataList = data.data.list;
        this.total = data.data.total;
      } else {
        this._notification.create("error", "错误提示", data.message);
      }
    });
  }

  //是否展示导出按钮
  isShowExport() {
    this.dataList.forEach(element =>{
      if(isNull(element.trainingPhoto) || element.checkInTable || element.summaryStatement){
      }
    });
  }

  delete(){
    if (JSON.parse(window.localStorage.getItem("user")).partyType != 4) {
      this._notification.create("warning", "警告提示", "您无权限");
      return;
    }
    const deleteList: any = [];
    const thiss: any = this;
    this.dataList.forEach(element => {
      if (element.checked) {
        deleteList.push(element.id);
      }
    });

    if (deleteList.length == 0) {
      // 异常
      this._notification.create("warning", "警告提示", "请选中一条数据！");
      return;
    }

    this.modalService.confirm({
      title: "您是否确认要删除这项内容",
      content: "<b>一旦删除，无法还原</b>",
      onOk() {
        let ob = thiss.httpService.deleteTrainingPlanDetail({ ids: deleteList }); //批量删除
        ob.subscribe(
          () => {
            thiss._notification.create("success", "成功", "删除成功！");
            thiss.trainingPlanDetail.currentPage = 1;
            thiss.query();
          },
          error => {
            this._notification.create("error", "错误提示", "删除失败！");
          }
        );
      },
      onCancel() { }
    });
  }

  update(title, content, footer){
    this.modelTitle = "修改";
    this.modal = 1;
    const updateList: any = [];

    this.dataList.forEach(element => {
      if (element.checked) {
        updateList.push(element);
        this.updateData = element;
      }
    });
    if (updateList.length > 1) {
      // 异常
      this._notification.create("warning", "警告提示", "只能选中一条数据！");
      return;
    }
    if (updateList.length == 0) {
      // 异常
      this._notification.create("warning", "警告提示", "请选中一条数据！");
      return;
    }
    this.currentModal = this.modalService.open({
      title: title,
      content: content,
      footer: footer,
      maskClosable: false,
      width: 800,
      style: {
        top: "20px"
      },
      onOk() {
        console.log("Click ok");
      }
    });
  }

  downloadFile(data, type) {
    //培训照片
    if (type == 1) {
      if (!data.trainingPhoto) {
        this._notification.create("error", "提示", "没有文件");
        return;
      }
      let list: any = data.trainingPhoto.split(",")
      for (let i = 0; i < list.length; i++) {
        let name1 = '培训现场照片' + (i + 1) + "." + list[i].split(".")[1];
        this.download(list[i], name1);
      }
    }
    //签到表
    if (type == 2) {
      if (!data.checkInTable) {
        this._notification.create("error", "提示", "没有文件");
        return;
      }
      let list: any = data.checkInTable.split(",")
      for (let i = 0; i < list.length; i++) {
        let name1 = '签到表' + (i + 1) + "." + list[i].split(".")[1];
        this.download(list[i], name1);
      }

    }
    //考核汇总表
    if (type == 3) {
      if (!data.summaryStatement) {
        this._notification.create("error", "提示", "没有文件");
        return;
      }
      let list: any = data.summaryStatement.split(",")
      for (let i = 0; i < list.length; i++) {
        let name1 = '考核汇总表' + (i + 1) + "." + list[i].split(".")[1];
        this.download(list[i], name1);
      }
    }
  }

  download(url, name) {
    let link = document.createElement('a');
    let body = document.querySelector('body');

    this.getBlob(this.config.IP + this.config.API.getUpload + url).then(blob => {
      link.href = window.URL.createObjectURL(blob);
      link.download = name;
      // fix Firefox
      link.style.display = 'none';
      body.appendChild(link);
      link.click();
      body.removeChild(link);
      window.URL.revokeObjectURL(link.href);
    });
  }

  getBlob(url) {
    return new Promise(resolve => {
      const xhr = new XMLHttpRequest();
      xhr.open('GET', url, true);
      xhr.responseType = 'blob';
      xhr.onload = () => {
        if (xhr.status === 200) {
          resolve(xhr.response);
        }
      };
      xhr.send();
    });
  }

  assignTask(){
    if (JSON.parse(window.localStorage.getItem("user")).partyType != 4) {
      this._notification.create("warning", "警告提示", "您无权限");
      return;
    }
    const trainingList: any = [];
    const partyList : any = [];
    this.dataList.forEach(element => {
      if (element.checked) {
        if(element.planStatus != 0){
          this._notification.create("warning", "警告提示", "该单位已经下达培训任务！");
        }else{
          trainingList.push(element.id);
          partyList.push(element.partyId);
        }
      }
    });

    if (trainingList.length == 0) {
      // 异常
      this._notification.create("warning", "警告提示", "请至少选中一条数据！");
      return;
    }
    let param = {
      ids : trainingList,
      planStatus : 1,
      partyIds : null,
      type : 'party',
      beUserId : this.userId,
    }
    param.partyIds = partyList.join(",");
    this.httpService.updateTrainingPlanStatus(param).subscribe(
      () => {
        this._notification.create("success", "成功", "下达任务成功！");
        this.trainingPlanDetail.currentPage = 1;
        this.query();
      },
      error => {
        this._notification.create("error", "错误提示", "下达任务失败！");

      }
    )
  }

  sendTrainingNotice(title, content, footer){
    if (JSON.parse(window.localStorage.getItem("user")).partyType != 4) {
      this._notification.create("warning", "警告提示", "您无权限");
      return;
    }

    const unitList: any = [];
    this.dataList.forEach(element => {
      if (element.checked) {
        if(element.planStatus == 0){
          this._notification.create("warning", "警告提示", "该单位未下达培训任务！");
        }else{
          unitList.push(element.partyId);
        }
      }
    });
    if (unitList.length == 0) {
      // 异常
      this._notification.create("warning", "警告提示", "请至少选中一条数据！");
      return;
    }

    this.modelTitle = "发送培训通知";
    this.modal = 2;
    this.currentModal = this.modalService.open({
      title: title,
      content: content,
      footer: footer,
      maskClosable: false,
      width: 800,
      style: {
        top: "20px"
      },
      onOk() {
        console.log("Click ok");
      }
    });
  }

  sendMessage() {
    const unitList: any = [];
    this.dataList.forEach(element => {
      if (element.checked) {
        if(element.planStatus == 0){
          this._notification.create("warning", "提示", "该单位未下达培训任务！");
        }else{
          unitList.push(element.partyId);
        }
      }
    });

    if (!this.sendTitle || !this.sendContent) {
      this._notification.create("error", "提示", "标题和内容必输!");
      return;
    }

    let param = {
      title: this.sendTitle,
      content: this.sendContent,
      id: JSON.parse(window.localStorage.getItem("user")).partyId,
      sendUserId: JSON.parse(window.localStorage.getItem("user")).id,
      partyIds:unitList,
    };
    this.httpService.batchMsg(param).subscribe(data => {
      if (data.status == 200) {
        this._notification.create("success", "提示", "通知成功");
        this.currentModal.destroy();
      } else {
        this._notification.create("error", "提示", "通知失败，请重试");
      }
    });
  }

  displayDataChange($event){
    this.dataList = $event;
    this.refreshStatus();
  }

  checkAll(value){
    if (value) {
      this.dataList.forEach(data => {
        if (!data.disabled) {
          data.checked = true;
        }
      });
    } else {
      this.dataList.forEach(data => data.checked = false);
    }
    this.refreshStatus();
  }

  //重置选择框
  refreshStatus() {
    const allChecked = this.dataList.every(
      value => value.disabled || value.checked
    );
    const allUnChecked = this.dataList.every(
      value => value.disabled || !value.checked
    );
    this.allChecked = allChecked;
    this.indeterminate = !allChecked && !allUnChecked;
  }
  //分页处理
  nzPageSizeChange(event){
    this.trainingPlanDetail.pageSize = event;
    this.trainingPlanDetail.currentPage = 1;
    this.query();
  }

  nzPageIndexChange(event){
    this.trainingPlanDetail.currentPage = event;
    this.query();
  }

  nzPageIndexClickChange(event){
    this.trainingPlanDetail.currentPage = event;
    this.query();
  }
  //添加返回
  addCall(event) {
    this.currentModal.destroy();
    this.query();
  }
  // 查询面板
  panels = {
    active: true,
    name: "查询",
    disabled: false,
    childPanel: [
      {
        active: false,
        name: "查询"
      }
    ]
  };
  toBack() {
    window.history.back();
  }
}
